﻿(function(window){
	var ajaxUrl = "http://192.168.100.35:8099";
	
	var STATUS ={
		'10' : '未确认',
		'12' : '匹配词条错误',
		'14' : '匹配词条成功',
		'16' : '匹配到多个词条',
		'17' : '无词条',
		'20' : '已复核'
	};

	/* 判断是否登录 */
	if(sessionStorage.getItem("userName")){

		/* 获取 用户类型 */
		var userRole = sessionStorage.getItem("userRole");

		if(userRole === "0"){
			/* 获取登录信息 */
			$("h5 .name").html(sessionStorage.getItem("userName"));

			bindEvent();
		}else{

			window.location.href = "../html/home.html";
		}

	}else{

		window.location.href = "../index.html";
	}

	/* 绑定事件 */
	function bindEvent(){

		/* tab 切换 */
		$(".option-list").on("click", "li", function(){

			if(!$(this).attr("data-status")){
				$(this).attr("data-status", true);

				var eventName = $(this).attr("data-event");
				page[eventName]();
			}

			$(this).addClass("active").siblings().removeClass("active");
			$(".option-content>li").eq($(this).index()).show().siblings().hide();
		});

		/* 下拉列表 */
		var pulldown = $(".pulldown");
		var input = $(".pulldown-input");
		input.focus(function(){
			if($(this).next().children().length > 0){
				$(this).next().stop().fadeIn();
			}
		});
		input.blur(function(){
			$(this).next().stop().fadeOut();
		});
		pulldown.on("click", "li", function(){
			$(this).parent().prev().val($(this).html());
			$(this).parent().stop().fadeOut();
		});

		/* 注销 */
		$(".logout").click(function(){
			if(confirm("您确定注销吗？")){
				sessionStorage.setItem("userName", "");
				sessionStorage.setItem("userRole", "");

				window.location.href = "../index.html";
			}
		});
	}

	var page = {
		/* 录入名言 */
		recordEvent: function(){
			var arr, str, val, html;
			$(".record-input").blur(function(){
				html = "";
				val = $(this).val().split("\n");
				for(var i = 0; i < val.length; i++){
					if(val[i] !== ""){
						str = $.trim(str);
						str = val[i].split("——");

						html += '<li>' +
									'<label><input class="btn-checkbox" type="checkbox" checked><span>'+ str[1] +'</span></label>' +
									'<p>'+ str[0] +'</p>' +
								'</li>';
					}
				}
				$(".record-output").html(html);
			});

			$(".record-submit").click(function(){
				arr = [];
				$(".record-output input:checked").each(function(){
					var author = $(this).next().html();
					var celebratedDictum = $(this).parent().next().html();

					arr.push({
						auth_name: author,
						motto_content: celebratedDictum
					});
				});

				/* 存储名言 */
				$.ajax({
					type: "POST",
					contentType: "application/json",
					data: JSON.stringify({list: arr}),
					url: ajaxUrl + "/api/motto",
					success: function(data){
						if(data.code === 1){
							if(data.data.errorCount){
								
								data.data.errorList.forEach(function(item){
									$(".record-output p").eq(item).css("color", "red");
								});
								dialog("<span style='color: red'>部分存储失败</span>");
							}else{
								dialog("<span>存储成功</span>");
							}
						}else{
							dialog("<span style='color: red'>"+ data.msg +"</span>");
						}
					},
					error: function(){
						dialog("<span style='color: red'>存储失败</span>");
					}
				});
			});
		},
		/* 复核名言 */
		reexamineEvent: function(){
			var arr = {};

			var request = {
				celebratedList: function(){
					/* 获取条件 */
					var keyword = $("#keyword1").val().trim();
					var status = $("#state").val().trim();
					
					if(status){
						for(var key in STATUS){
							if(STATUS[key] === status){
								status = key; 
								break;
							} 
						}
					}

					$.ajax({
						type: "GET",
						contentType: "application/json",
						data: {
							keyword: keyword,
							status: status
						},
						url: ajaxUrl + "/api/Motto",
						success: function(data){
							if(data.code === 1){
								var html = "";
								data.data.forEach(function(item){
									html += "<tr data-id='"+ item.id +"' data-item='"+ JSON.stringify(item) +"'>";

									html += "<td>"+ item.auth_Name +"</td>";
									html += "<td>"+ item.motto_Content +"</td>";
									html += "<td class='text-center'>"+ STATUS[item.status] +"</td>";

									html += "</tr>";
								});

								$("#celebratedList tbody").html(html);
								$("#celebratedList tbody tr:first").click();
								
							}else{
								dialog("<span style='color: red'>"+ data.msg +"</span>");
							}
						},
						error: function(){
							dialog("<span style='color: red'>查询失败</span>");
						}
					});
				},
				changeItem: function(data, callback){
					$.ajax({
						type: "POST",
						contentType:"application/json",
						data: JSON.stringify(data),
						url: ajaxUrl + "/api/mottoreview",
						success: function(data){
							if(data.code === 1){

								dialog("修改成功");
								callback();
								
							}else{
								dialog("<span style='color: red'>"+ data.msg +"</span>");
							}
						},
						error: function(){
							dialog("<span style='color: red'>修改失败</span>");
						}
					});
				}
			}

			/* 详情 */
			$("#celebratedList").on("click", "tbody tr", function(){

				$(this).addClass("active").siblings().removeClass("active");
				
				var details = JSON.parse($(this).attr("data-item"));

				requestLabel($("#reexamine-list"));

				$(".reexamine-operation").attr('data-id', details.id);

				/* 查询 百度百科 */
				$.ajax({
					type: "GET",
					contentType:"application/json",
					data: {
						mottoId: details.id
					},
					url: ajaxUrl + "/api/MottoBaike",
					success: function(data){
						if(data.code === 1){
							if(data.data.baikeCount > 0){
								var list = "";
								var linkList = JSON.parse(data.data.baikeContent);

								linkList.map(function(item){
									var checked = details.baike_Url && details.baike_Url === item.BaiKeUrl; 
									list += '<tr>';

									list += '<td class="text-center"><input type="radio" data-url="'+ item.BaiKeUrl +'" class="btn-radio" name="radio" '+ (checked ? "checked" : "") +'></td>'
									list += '<td><a href="'+ item.BaiKeUrl +'" target="_blank">'+ item.Title +'</a></td>'

									list += '</tr>';
								});
								$(".reexamine-option tbody").html(list);

								$("#reexamine-label").val(details.tagList ? details.tagList : "").parent().show();
								$(".reexamine-confirm").prop("disabled", "");
							}else{
								$(".reexamine-option tbody").html("<tr><td></td><td>无词条</td></tr>");

								$("#reexamine-label").parent().hide();
								$(".reexamine-confirm").prop("disabled", "disabled");
							}
						}else{
							dialog("<span style='color: red'>查询失败</span>");
							$(".reexamine-option tbody").html("<tr><td></td><td>查询失败</td></tr>");

							$("#reexamine-label").parent().hide();
							$(".reexamine-confirm").prop("disabled", "disabled");
						}
					},
					error: function(){
						dialog("<span style='color: red'>查询失败</span>");
					}
				});
			});

			/* 跳过 */
			$(".reexamine-skip").click(function(){
				var id = $(this).parent().attr("data-id");

				var dom = $("#celebratedList tbody tr[data-id="+ id +"]");
				dom.next().click();
			});
			/* 确定 */
			$(".reexamine-confirm").click(function(){
				var id = $(this).parent().attr("data-id");

				var dom = $("#celebratedList tbody tr[data-id="+ id +"]");
				var checked = $(".reexamine-option table input:checked");

				var item = JSON.parse(dom.attr("data-item"));

				if(checked.length > 0){
					var parameter = {
						id: id,
						baike_Url: $(".reexamine-option table input:checked").attr("data-url"),
						tagList: $("#reexamine-label").val()
					}

					/* 保存 */
					request.changeItem(parameter, function(){
						item.baike_Url = parameter.baike_Url;
						item.tagList = parameter.tagList;
						dom.attr("data-item", JSON.stringify(item)).next().click();
						dom.children().eq(2).html("已复核");
					});
				}else{
					dialog("<span style='color: red'>必须选择词条！</span>");
				}
			});

			/* 搜索 */
			$("#seek").click(request.celebratedList);

			/* 请求 列表 */
			request.celebratedList();
		},
		/* 配置名言 */
		configurationEvent: function(){
			var fun = {
				bindDatetimepicker: function(){
					$('#startTime, #endTime').datetimepicker({
					    language: 'zh-CN',
					    weekStart: 1,
					    todayBtn: "linked",
					    autoclose: true,
					    clearBtn: true,
					    todayHighlight: true,
					    startView: 2,
					    minView: 2,
					    maxView: 4,
					    format: 'yyyy-mm-dd',

					    autoclose: 1,

					    initialDate: new Date(),

					    forceParse: 0,

					    container: 'body',

					    endDate: null
					});
				},
				renderList: function(data){

					var html = '';
					data.map(function(item){
						var stringItem = JSON.stringify(item);
						html += "<tr>";

						html += "<td>"+ item.rule_Name +"</td>";
						html += "<td>"+ item.startDate.substring(0, 10) +" ~ "+ item.endDate.substring(0, 10) +"</td>";
						html += "<td><button class='change' data-item='"+ stringItem +"'><i class='iconfont icon-icon_main_edit_defau'></i></button> <button class='delete' data-id='"+ item.id +"'><i class='iconfont icon-icon_main_delete_def1'></i></button></td>";

						html += "</tr>";
					});
					return html;
				},
				setCondition: function(data){
					if(data){
						$("#startTime").val(data.startDate.substring(0, 10));
						$("#endTime").val(data.endDate.substring(0, 10));
						$("#title").val(data.rule_Name);
						$("#isMatchingFlag").prop("checked", data["usedefaultRule"] ? true : false).attr("data-id", data["id"]);

						var json = JSON.parse(data.rule_Json);
						$("#label").val(json.label);
						$("#Author").val(json.Author);
						$("#keyword").val(json.keyword);
						$("#yearly").prop("checked", json.yearly);
					}else{
						/* 清空条件 */
						$(".configuration-option input[type=text]").val("");
						$(".configuration-option input[type=checkbox]").prop("checked", false).attr("data-id", "");
					}
				},
				getCondition: function(){
					var itemConfig = {
						startDate: $("#startTime").val(),
						endDate: $("#endTime").val(),
						rule_Name: $("#title").val(),
						usedefaultRule: Number($("#isMatchingFlag").prop("checked")),
						id: $("#isMatchingFlag").attr("data-id"),
						rule_Json: JSON.stringify({
							label: $("#label").val(),
							Author: $("#Author").val(),
							keyword: $("#keyword").val(),
							yearly: $("#yearly").prop("checked")
						})
					};

					return itemConfig;
				},
				resetInput: function(){
					fun.setCondition(false);
					$(".configuration-container").removeClass("compile-flag");
				},
				checkList: function(data){
					if(data.startDate === "" || data.endDate === ""){
						dialog("<span style='color: red'>开始时间和结束时间不能为空!</span>");
						return false;
					}

					if(data.rule_Name === ""){
						dialog("<span style='color: red'>标题不能为空！</span>");
						return false;
					}

					var rule_Json = JSON.parse(data.rule_Json);
					if(rule_Json.Author === ""
						&& rule_Json.keyword === ""
						&& rule_Json.label === ""){
						dialog("<span style='color: red'>标签、作者、关键字至少填写一个！</span>");
						return false;
					}

					return true;
				}
			}

			var request = {
				/* 修改 配置 */
				changeCondition: function(data, callback){
					console.log(data);
					$.ajax({
						type: "POST",
						contentType:"application/json",
						data: JSON.stringify(data),
						url: ajaxUrl + "/api/mottorule",
						success: function(data){
							if(data.code === 1){
								
								callback();
								dialog("<span>修改成功</span>");
							}else{
								dialog("<span style='color: red'>"+ data.msg +"</span>");
							}
						},
						error: function(){
							dialog("<span style='color: red'>修改失败</span>");
						}
					});
				},
				/* 添加 配置 */
				addCondition: function(data, callback){
					$.ajax({
						type: "POST",
						data: JSON.stringify(data),
						contentType:"application/json",
						url: ajaxUrl + "/api/mottorule",
						success: function(data){
							if(data.code === 1){
								
								callback();
								dialog("<span>添加成功</span>");
							}else{
								dialog("<span style='color: red'>"+ data.msg +"</span>");
							}
						},
						error: function(){
							dialog("<span style='color: red'>添加失败</span>");
						}
					});
				},
				/* 删除 配置 */
				deleteCondition: function(id, callback){
					$.ajax({
						type: "DELETE",
						contentType:"application/json",
						url: ajaxUrl + "/api/mottorule/" + id,
						success: function(data){
							if(data.code === 1){
								
								callback();
								dialog("<span>删除成功</span>");
							}else{
								dialog("<span style='color: red'>"+ data.msg +"</span>");
							}
						},
						error: function(){
							dialog("<span style='color: red'>删除失败</span>");
						}
					});
				}
			}
			
			/* 请求 配置列表 */
			$.get(ajaxUrl + "/api/mottorule", function(data){
				$("#configuration-list tbody").html(fun.renderList(data.data.dataList));
			});

			/* 设置 标签 */
			requestLabel($("#configuration-label"));

			/* 添加日期控件 */
			fun.bindDatetimepicker();

			/* 修改 */
			$("#configuration-list").on("click", ".change", function(){
				var itemConfig = $(this).attr("data-item");
				itemConfig = JSON.parse(itemConfig);
				
				fun.setCondition(itemConfig);
				$(".configuration-container").addClass("compile-flag");
			});

			/* 删除 */
			$("#configuration-list").on("click", ".delete", function(){
				var id = $(this).attr("data-id");
				var dom = $(this).parents("tr");

				if(confirm("您确定删除吗？")){
					request.deleteCondition(id, function(){
						dom.remove();
					});
				}
			});

			/* 添加 */
			$(".configuration-container").on("click", ".add", function(){

				var itemConfig = fun.getCondition();

				if(fun.checkList(itemConfig)){
					request.addCondition(itemConfig, function(){

						var html = fun.renderList([itemConfig]);

						$("#configuration-list tbody").append(html);

						fun.setCondition(false);

						/* 重新设置标签 */
						requestLabel($("#configuration-label"));
					});
				}
			});

			/* 确定 */
			$(".compile").on("click", ".confirm", function(){

				var itemConfig = fun.getCondition();

				if(fun.checkList(itemConfig)){
					request.changeCondition(itemConfig, function(){
						fun.resetInput();
						var dom = $("#configuration-list .delete[data-id="+ itemConfig["id"] +"]").parents("tr");
						var html = fun.renderList([itemConfig]);

						dom.after(html).remove();

						/* 重新设置标签 */
						requestLabel($("#configuration-label"));
					});
				}
			});
			/* 取消 */
			$(".compile").on("click", ".cancel", fun.resetInput);
		}
	}

	/* 请求 标签 */
	function requestLabel(dom){
		$.ajax({
			type: "GET",
			contentType:"application/json",
			url: ajaxUrl + "/api/target",
			success: function(data){
				if(data.code === 1){
					console.log(data)
					var html = "";
					data.data.map(function(item){
						html += "<li>"+ item +"</li>"
					});
					dom.html(html);
				}else{
					dialog("<span style='color: red'>"+ data.msg +"</span>");
				}
			},
			error: function(){
				dialog("<span style='color: red'>标签请求失败</span>");
			}
		});
	}

	/* 弹框 */
	function dialog(msg){

		var html = '<li>' + msg + '</li>'
		$(".dialog").append(html);

		var lastLi = $(".dialog li:last");

		lastLi.fadeToggle("slow");

		setTimeout(function(){
			lastLi.fadeToggle("slow", function(){
				lastLi.remove();
			});
		}, 2000);
	}
})(window);